<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生命周期</title>
</head>

<body>
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
<!-- 引入react核心库 -->
<script type="text/javascript" src="../js/react.development.js"></script>
<!-- 引入react-dom，用于支持react操作DOM -->
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<!-- 设置props的类型 -->
<script type="text/javascript" src="../js/prop-types.js"></script>
<!-- 引入babel，用于将jsx转为js -->
<script type="text/javascript" src="../js/babel.min.js"></script>

<script type="text/babel">
    class Life extends React.Component {

        constructor(props) {
            super(props);
            this.state = {
                opacity: 1
            }
            // this.destroyComponent = this.destroyComponent.bind(this)
        }


        destroyComponent = () => {
            ReactDOM.unmountComponentAtNode(document.getElementById('demo1'))
        }

        // render执行之前的方法
        componentWillMount() {
            console.log("componentWillMount");
        }

        // render 方法执行后 会执行这个方法
        componentDidMount = () => {
            //启动循环执行器
            this.timer = setInterval(function () {
                console.log("定时器执行");
                let {opacity} = this.state
                opacity -= 0.1
                if (opacity <= 0) {
                    opacity = 1
                }
                this.setState({opacity},(function () {
                    console.log("setState的回调函数");
                }))
                //setState()=>componentWillUpdate()=>render()=>componentDidUpdate=>setState回调函数
            }.bind(this), 200);
        }




        //更新状态的生命周期函数 render 之前
        //setState()=>componentWillUpdate()=>render()
        componentWillUpdate = () => {
            console.log("componentWillUpdate");
        }
        //更新状态的生命周期函数 render 之后
        //setState()=>componentWillUpdate()=>render()=>componentDidUpdate
        componentDidUpdate = () => {
            console.log("componentDidUpdate");
        }


        //组件销毁后会执行的方法 用清除定时器 防止内存泄漏
        componentWillUnmount = () => {
            console.log("componentWillUnmount");
            clearInterval(this.timer)
        }

        render() {
            console.log("render");
            const {opacity} = this.state
            return (
                <div>
                    <h2 style={{opacity: opacity}}>
                        {this.props.msg}
                    </h2>
                    <button onClick={this.destroyComponent}> 不活了</button>
                </div>
            )
        }
    }


    ReactDOM.render(<Life msg="太难了"/>, document.getElementById('demo1'))
</script>
</body>

</html>
